package Email.auto.checker;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.spec.InvalidKeySpecException;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Main class.
 * 
 * @author Marcio Almeida
 * @author Mario Marques
 * @author Helder Lopes
 * @author Emanuel Bicho
 * @author Andre Duarte
 * 
 */
public class Main {

	/**
	 * String email : containing a string with email stored in a file
	 */
	private static String email = null;
	/**
	 * Contains the password stored in the file.
	 */
	private static String pass = null;
	/**
	 * Comunication comunication: Reference to comunication module
	 */
	private static Comunication comunication = null;
	/**
	 * Tray tray: Reference to tray module of program (main interface)
	 */
	private static Tray tray = null;

	/**
	 * The static main method used to start the application.
	 * 
	 * @param args
	 *            - command line args
	 */
	public static void main(final String[] args) {

		DESEncryption des = null;
		File f = null;
		byte[] bin = null;
		FileInputStream fin = null;
		String fileData = null;

		try {
			comunication = new Comunication();

			des = new DESEncryption("umachave");
			f = new File("actAccount.dat");
			bin = new byte[(int) f.length()];

			fileData = null;

			fin = new FileInputStream(f);
			fin.read(bin);
			fin.close();

			fileData = des.desencrypt(bin);
			StringTokenizer token = new StringTokenizer(fileData, " ");
			email = token.nextToken();
			pass = token.nextToken();

			if (comunication.validaActualUser(email, pass)) {
				Account account = new Account(tray, comunication);
				account.setEmail(email);
				account.setPass(pass);
				account.setDomain(account.getDomainFromEmail(email));
				account.setInvible();

				tray = new Tray(comunication, account, des);

				Timer t = new Timer();
				TimerTask timerControl = new TimerControl(comunication, account);
				t.scheduleAtFixedRate(timerControl,
						ConstComunication.FIFTEEN_MINUTES,
						ConstComunication.FIFTEEN_MINUTES);

				tray.setT(t);
			} else {
				ErrorNotification.showErrorMessage(null,
						ConstErrorNotification.LOGIN_ERROR);
			}

		} catch (FileNotFoundException e1) {
			System.out.println("Nao existe ficheiro: " + e1.toString());
			tray = new Tray(comunication, null, des);
		} catch (IOException e) {
			System.out.println("Erro ao ler do ficheiro...");
		} catch (InvalidKeySpecException e) {
			System.out.println("Invalid key: " + e.toString());
		} catch (InvalidKeyException e) {
			System.out.println("Invalid key size: " + e.toString());
		} catch (NullPointerException e) {
			System.out.println("The key is null: " + e.toString());
		}
	}

}
